<template>
	<view class="setting-page">
		<!-- 设置列表容器 -->
		<view class="setting-container">
			<!-- 账号与安全 -->
			<view class="setting-group">
				<view class="group-title">账号与安全</view>
				<view class="setting-list">
					<view class="setting-item" @click="goToPage('/pages/user/accountSec')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-security.png"></image>
							<text class="item-title">账号安全</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
					<!-- 手机号绑定（从会话存储获取） -->
					<view class="setting-item" @click="goToPhoneBind">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-phone.png"></image>
							<text class="item-title">手机号绑定</text>
						</view>
						<text class="item-desc">{{ formattedMobile }}</text>
						<text class="item-right-icon">→</text>
					</view>
					<view class="setting-item" @click="goToPage('/pages/user/password')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-lock.png"></image>
							<text class="item-title">修改密码</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
				</view>
			</view>

			<!-- 功能设置（美食相关） -->
			<view class="setting-group">
				<view class="group-title">美食功能设置</view>
				<view class="setting-list">
					<view class="setting-item">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-notice.png"></image>
							<text class="item-title">美食通知</text>
						</view>
						<switch v-model="noticeSwitch" @change="handleNoticeChange" color="#ff7a45"></switch>
					</view>
					<view class="setting-item" @click="goToAddressList">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-address.png"></image>
							<text class="item-title">收货地址管理</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
					<view class="setting-item" @click="clearCache" :class="{ loading: isClearing }">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-cache.png"></image>
							<text class="item-title">清除美食缓存</text>
						</view>
						<view class="item-right">
							<text class="cache-size">{{ cacheSize }}M</text>
							<text class="item-right-icon">→</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 帮助与服务 -->
			<view class="setting-group">
				<view class="group-title">美食服务中心</view>
				<view class="setting-list">
					<view class="setting-item" @click="goToPage('/pages/user/help')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-service.png"></image>
							<text class="item-title">美食客服</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
					<view class="setting-item" @click="goToPage('/pages/enter/feedback')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-service.png"></image>
							<text class="item-title">留言反馈</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
					<view class="setting-item" @click="goToPage('/pages/user/about')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-about.png"></image>
							<text class="item-title">关于美食APP</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
					<view class="setting-item">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-version.png"></image>
							<text class="item-title">当前版本</text>
						</view>
						<text class="version-text">v1.0.0</text>
						<text class="check-update" @click="checkVersionUpdate">检查更新</text>
					</view>
					<view class="setting-item" @click="goToPage('/pages/enter/contactUs')">
						<view class="item-left">
							<image class="item-thumb" src="/static/images/food-service.png"></image>
							<text class="item-title">联系我们</text>
						</view>
						<text class="item-right-icon">→</text>
					</view>
				</view>
			</view>

			<!-- 退出登录 -->
			<view class="logout-container" v-if="isLogin">
				<button class="logout-btn" @click="onClickLogout" :disabled="isLoggingOut">
					退出美食账号
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	// 存储工具函数（修改为会话存储sessionStorage）
	const storage = {
		getToken: () => {
			try {
				// 从会话存储获取token
				return sessionStorage.getItem("token") || "";
			} catch (err) {
				return "";
			}
		},
		getUser: () => {
			try {
				// 从会话存储获取用户信息
				const userStr = sessionStorage.getItem("user");
				return userStr ? JSON.parse(userStr) : {};
			} catch (err) {
				sessionStorage.removeItem("user");
				return {};
			}
		},
		removeToken: () => sessionStorage.removeItem("token"),
		removeUser: () => sessionStorage.removeItem("user"),
		// 通知开关仍使用本地存储（持久化）
		getNoticeSwitch: () => {
			try {
				const val = uni.getStorageSync("noticeSwitch");
				return val !== undefined ? val : true;
			} catch (err) {
				return true;
			}
		},
		setNoticeSwitch: (val) => uni.setStorageSync("noticeSwitch", val)
	};

	// 工具函数：手机号格式化
	const formatPhone = (phone) => {
		return phone && phone.length === 11 ? phone.replace(/^(\d{3})(\d{4})(\d{4})$/, "$1****$3") : phone;
	};

	export default {
		data() {
			return {
				noticeSwitch: storage.getNoticeSwitch(),
				cacheSize: "0.0",
				isClearing: false,
				isLoggingOut: false,
				isLogin: false,
				userMobile: "" // 从会话存储获取的手机号
			};
		},

		computed: {
			// 计算属性优化手机号渲染逻辑
			formattedMobile() {
				return this.isLogin && this.userMobile ? formatPhone(this.userMobile) : "未绑定";
			}
		},

		onLoad() {
			this.calculateCacheSize();
			this.checkLoginStatus();
		},

		onShow() {
			this.checkLoginStatus(); // 每次显示页面重新检查会话存储中的信息
		},

		methods: {
			// 检查登录状态与手机号（从会话存储获取）
			checkLoginStatus() {
				const token = storage.getToken();
				const userInfo = storage.getUser();
				this.isLogin = !!token;
				// 从会话存储的用户信息中提取手机号
				this.userMobile = this.isLogin ? (userInfo.phone || userInfo.mobile || "") : "";
			},

			// 页面跳转（统一封装）
			navigateTo(url) {
				uni.navigateTo({
					url
				});
			},

			goToUserCenter() {
				this.navigateTo("/pages/user/userCenter");
			},

			goToAddressList() {
				this.navigateTo("/pages/address/addressList");
			},

			goToPage(url) {
				this.navigateTo(url);
			},

			// 手机号绑定页面跳转
			goToPhoneBind() {
				this.navigateTo("/pages/user/phoneBind");
			},

			// 通知开关变更
			handleNoticeChange(e) {
				const val = e.detail.value;
				this.noticeSwitch = val;
				storage.setNoticeSwitch(val);
				uni.showToast({
					title: val ? "美食通知已开启" : "美食通知已关闭",
					icon: "none",
					duration: 1500
				});
			},

			// 计算缓存大小
			calculateCacheSize() {
				try {
					const storageInfo = uni.getStorageInfoSync();
					// 转换为MB并保留1位小数
					this.cacheSize = (storageInfo.currentSize / (1024 * 1024)).toFixed(1);
				} catch (err) {
					this.cacheSize = "2.3";
				}
			},

			// 清除缓存
			clearCache() {
				if (this.isClearing) return;
				this.isClearing = true;

				uni.showModal({
					title: "清除美食缓存",
					content: "清除美食图片缓存、浏览记录等临时数据",
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: "清除中..."
							});
							try {
								await uni.clearStorageSync();
								this.calculateCacheSize();
								uni.showToast({
									title: "清除成功",
									icon: "success"
								});
							} catch (err) {
								uni.showToast({
									title: "清除失败",
									icon: "none"
								});
							} finally {
								this.isClearing = false;
								uni.hideLoading();
							}
						} else {
							this.isClearing = false;
						}
					},
					fail: () => {
						this.isClearing = false;
					}
				});
			},

			// 检查版本更新
			checkVersionUpdate() {
				uni.showLoading({
					title: "检查中..."
				});
				setTimeout(() => {
					uni.hideLoading();
					uni.showModal({
						title: "版本检查",
						content: "当前已是美食APP最新版本v1.0.0",
						showCancel: false
					});
				}, 800);
			},

			// 退出登录（同时清除会话存储）
			onClickLogout() {
				if (this.isLoggingOut) return;
				this.isLoggingOut = true;

				uni.showModal({
					title: "确认退出",
					content: "退出后将无法查看美食订单、收藏等个人信息",
					success: (res) => {
						if (res.confirm) {
							try {
								storage.removeToken(); // 清除会话存储的token
								storage.removeUser(); // 清除会话存储的用户信息
								uni.showToast({
									title: "退出成功",
									icon: "success"
								});
								setTimeout(() => {
									uni.switchTab({
										url: "/pages/user/user"
									});
								}, 1000);
							} catch (err) {
								uni.showToast({
									title: "退出失败",
									icon: "none"
								});
								this.isLoggingOut = false;
							}
						} else {
							this.isLoggingOut = false;
						}
					},
					fail: () => {
						this.isLoggingOut = false;
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.setting-page {
		background-color: #fff8f2;
		min-height: 100vh;
	}

	// 设置容器
	.setting-container {
		padding: 16px;
	}

	// 分组标题
	.setting-group {
		margin-bottom: 16px;

		.group-title {
			font-size: 14px;
			color: #ff7a45;
			margin-bottom: 8px;
			font-weight: 600;
		}
	}

	// 列表样式
	.setting-list {
		background-color: #fff;
		border-radius: 12px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(255, 122, 69, 0.1);
	}

	// 列表项
	.setting-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px;
		border-bottom: 1px solid #fff8f2;
		transition: background-color 0.1s ease;

		&:last-child {
			border-bottom: none;
		}

		&:active {
			background-color: #fff5ed;
		}

		&.loading {
			opacity: 0.7;
			pointer-events: none;
		}

		.item-left {
			display: flex;
			align-items: center;
		}

		.item-thumb {
			width: 26px;
			height: 26px;
			margin-right: 12px;
			object-fit: contain;
		}

		.item-title {
			font-size: 16px;
			color: #333;
			font-weight: 500;
		}

		.item-right {
			display: flex;
			align-items: center;
		}

		.item-desc {
			font-size: 14px;
			color: #666;
			margin-right: 8px;
		}

		.item-right-icon {
			font-size: 16px;
			color: #ff7a45;
		}
	}

	// 缓存大小
	.cache-size {
		font-size: 14px;
		color: #666;
	}

	// 版本信息
	.version-text {
		font-size: 14px;
		color: #666;
	}

	.check-update {
		margin-left: 12px;
		font-size: 14px;
		color: #ff7a45;
	}

	// 退出登录按钮
	.logout-container {
		margin: 20px 16px 0;

		.logout-btn {
			width: 100%;
			background-color: #fff;
			color: #ff7a45;
			border: 1px solid #ff7a45;
			border-radius: 12px;
			padding: 12px 0;
			font-size: 16px;
			font-weight: 500;
		}
	}
</style>